package com.song.coresegandreduce;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.apache.commons.collections.map.MultiValueMap;

import com.song.corebean.mapred.MapReduce;
import com.song.corebean.utils.Utils;

public class DealCore implements MapReduce<String ,Map<String,Integer>> {

	public List<List<String>> seg(List<String> list, int count) {
		// TODO Auto-generated method stub
		return Utils.segList(list, count);
	}

	

	public void initConfig() {
		System.setProperty("user.dir", "./");
		
	}

	public List<Map<String, Integer>> deal(List<String> datas) {
		Map<String, Integer> data = new  HashMap<String, Integer>();
		List<Map<String, Integer>> results = new ArrayList<Map<String,Integer>>();
		for(String bean :datas)
		{
			  Map<String,Integer> map = dealBean(bean);
			  results.add(map);
		}
		return results;
	}
	
	
	public Map<String, Integer> dealBean(String s) {
		List<Term> tems =  ToAnalysis.parse(s);
		Map<String,Integer> count = new HashMap<String, Integer>();
		MultiValueMap map = new MultiValueMap();
		for(Term  term :tems)
		{
			map.put(term.getName(),term.getName());
		}
		
		for(Object key :map.keySet())
		{
			count.put(key.toString(), map.getCollection(key).size());
		}
		return count;
	}



	public Map<String, Integer> reduce(List<List<Map<String, Integer>>> datas) {
			Map<String, Integer> data = new  HashMap<String, Integer>();
			for( List<Map<String, Integer>>  dd :datas)
			{
				for(Map<String, Integer> map :dd)
				{
					for(Entry<String, Integer> entry :map.entrySet())
					{
						if(data.containsKey(entry.getKey()))
						{
							data.put(entry.getKey(), data.get(entry.getKey())+entry.getValue());
						}else{
							data.put(entry.getKey(), entry.getValue());
						}
					}
				}
			}
			return data;
	}
}
